"""
Web API路由模块

提供RESTful API接口
"""

import json
from datetime import datetime, timedelta
from typing import Dict, Any, Optional, List
from flask import Blueprint, jsonify, request, current_app

from ..core import unified_logger
from ..monitoring import unified_monitor


class APIRouter:
    """API路由器"""
    
    def __init__(self, monitor=None):
        """
        初始化API路由器
        
        Args:
            monitor: 监控实例
        """
        self.monitor = monitor or unified_monitor
        self.logger = unified_logger.get_logger('api_router')
        
        # 创建蓝图
        self.bp = Blueprint('api', __name__, url_prefix='/api')
        
        # 注册路由
        self._register_routes()
        
        self.logger.info("API路由器初始化完成")
    
    def register_routes(self, app):
        """注册路由到Flask应用"""
        app.register_blueprint(self.bp)
        self.logger.info("API路由已注册")
    
    def _register_routes(self):
        """注册所有API路由"""
        
        # 监控面板数据
        @self.bp.route('/dashboard/data')
        def get_dashboard_data():
            """获取监控面板数据"""
            try:
                force_refresh = request.args.get('refresh', 'false').lower() == 'true'
                data = self.dashboard.get_dashboard_data(force_refresh)
                return jsonify({
                    'success': True,
                    'data': data
                })
            except Exception as e:
                self.logger.error(f"获取面板数据失败: {e}")
                return jsonify({
                    'success': False,
                    'error': str(e)
                }), 500
        
        # 系统健康状态
        @self.bp.route('/system/health')
        def get_system_health():
            """获取系统健康状态"""
            try:
                health = self.dashboard.get_system_health()
                return jsonify({
                    'success': True,
                    'data': health
                })
            except Exception as e:
                self.logger.error(f"获取系统健康状态失败: {e}")
                return jsonify({
                    'success': False,
                    'error': str(e)
                }), 500
        
        # 系统指标
        @self.bp.route('/system/metrics')
        def get_system_metrics():
            """获取系统指标"""
            try:
                hours = int(request.args.get('hours', 1))
                if not self.dashboard.system_monitor:
                    return jsonify({
                        'success': False,
                        'error': '系统监控未启用'
                    }), 400
                
                current_metrics = self.dashboard.system_monitor.get_current_metrics()
                history = self.dashboard.system_monitor.get_metrics_history(hours)
                
                return jsonify({
                    'success': True,
                    'data': {
                        'current': {
                            'cpu_percent': current_metrics.cpu_percent if current_metrics else 0,
                            'memory_percent': current_metrics.memory_percent if current_metrics else 0,
                            'disk_percent': current_metrics.disk_percent if current_metrics else 0,
                            'process_count': current_metrics.process_count if current_metrics else 0,
                            'timestamp': current_metrics.timestamp.isoformat() if current_metrics else None
                        },
                        'history': [
                            {
                                'timestamp': m.timestamp.isoformat(),
                                'cpu_percent': m.cpu_percent,
                                'memory_percent': m.memory_percent,
                                'disk_percent': m.disk_percent,
                                'process_count': m.process_count
                            }
                            for m in history
                        ]
                    }
                })
            except Exception as e:
                self.logger.error(f"获取系统指标失败: {e}")
                return jsonify({
                    'success': False,
                    'error': str(e)
                }), 500
        
        # 策略列表
        @self.bp.route('/strategies')
        def get_strategies():
            """获取策略列表"""
            try:
                if not self.dashboard.strategy_monitor:
                    return jsonify({
                        'success': False,
                        'error': '策略监控未启用'
                    }), 400
                
                strategies = self.dashboard.strategy_monitor.get_all_strategies_status()
                performance = self.dashboard.strategy_monitor.get_performance_summary()
                
                return jsonify({
                    'success': True,
                    'data': {
                        'strategies': strategies,
                        'performance': performance
                    }
                })
            except Exception as e:
                self.logger.error(f"获取策略列表失败: {e}")
                return jsonify({
                    'success': False,
                    'error': str(e)
                }), 500
        
        # 单个策略详情
        @self.bp.route('/strategies/<strategy_name>')
        def get_strategy_detail(strategy_name):
            """获取策略详情"""
            try:
                if not self.dashboard.strategy_monitor:
                    return jsonify({
                        'success': False,
                        'error': '策略监控未启用'
                    }), 400
                
                hours = int(request.args.get('hours', 24))
                status = self.dashboard.strategy_monitor.get_strategy_status(strategy_name)
                history = self.dashboard.strategy_monitor.get_strategy_history(strategy_name, hours)
                
                return jsonify({
                    'success': True,
                    'data': {
                        'status': status,
                        'history': [
                            {
                                'timestamp': m.timestamp.isoformat(),
                                'total_profit': m.total_profit,
                                'daily_profit': m.daily_profit,
                                'total_trades': m.total_trades,
                                'win_rate': m.win_rate,
                                'max_drawdown': m.max_drawdown,
                                'status': m.status
                            }
                            for m in history
                        ]
                    }
                })
            except Exception as e:
                self.logger.error(f"获取策略详情失败: {e}")
                return jsonify({
                    'success': False,
                    'error': str(e)
                }), 500
        
        # 告警列表
        @self.bp.route('/alerts')
        def get_alerts():
            """获取告警列表"""
            try:
                if not self.dashboard.alert_manager:
                    return jsonify({
                        'success': False,
                        'error': '告警管理未启用'
                    }), 400
                
                status = request.args.get('status', 'active')
                level = request.args.get('level')
                limit = int(request.args.get('limit', 100))
                
                if status == 'active':
                    alerts = self.dashboard.alert_manager.get_active_alerts()
                else:
                    hours = int(request.args.get('hours', 24))
                    alerts = self.dashboard.alert_manager.get_alert_history(hours)
                
                # 过滤级别
                if level:
                    try:
                        alert_level = AlertLevel(level.upper())
                        alerts = [a for a in alerts if a.level == alert_level]
                    except ValueError:
                        pass
                
                # 限制数量
                alerts = alerts[:limit]
                
                # 转换为字典
                alerts_data = [
                    {
                        'id': alert.id,
                        'title': alert.title,
                        'message': alert.message,
                        'level': alert.level.value,
                        'status': alert.status.value,
                        'created_at': alert.created_at.isoformat(),
                        'resolved_at': alert.resolved_at.isoformat() if alert.resolved_at else None,
                        'tags': alert.tags,
                        'data': alert.data
                    }
                    for alert in alerts
                ]
                
                return jsonify({
                    'success': True,
                    'data': {
                        'alerts': alerts_data,
                        'total': len(alerts_data)
                    }
                })
            except Exception as e:
                self.logger.error(f"获取告警列表失败: {e}")
                return jsonify({
                    'success': False,
                    'error': str(e)
                }), 500
        
        # 解决告警
        @self.bp.route('/alerts/<alert_id>/resolve', methods=['POST'])
        def resolve_alert(alert_id):
            """解决告警"""
            try:
                if not self.dashboard.alert_manager:
                    return jsonify({
                        'success': False,
                        'error': '告警管理未启用'
                    }), 400
                
                data = request.get_json() or {}
                comment = data.get('comment', '')
                
                success = self.dashboard.alert_manager.resolve_alert(alert_id, comment)
                
                return jsonify({
                    'success': success,
                    'message': '告警已解决' if success else '告警解决失败'
                })
            except Exception as e:
                self.logger.error(f"解决告警失败: {e}")
                return jsonify({
                    'success': False,
                    'error': str(e)
                }), 500
        
        # 告警统计
        @self.bp.route('/alerts/stats')
        def get_alert_stats():
            """获取告警统计"""
            try:
                if not self.dashboard.alert_manager:
                    return jsonify({
                        'success': False,
                        'error': '告警管理未启用'
                    }), 400
                
                stats = self.dashboard.alert_manager.get_stats()
                rule_stats = self.dashboard.alert_manager.get_rule_stats()
                
                return jsonify({
                    'success': True,
                    'data': {
                        'alert_stats': stats,
                        'rule_stats': rule_stats
                    }
                })
            except Exception as e:
                self.logger.error(f"获取告警统计失败: {e}")
                return jsonify({
                    'success': False,
                    'error': str(e)
                }), 500
        
        # 通知器状态
        @self.bp.route('/notifications/status')
        def get_notification_status():
            """获取通知器状态"""
            try:
                if not self.dashboard.notification_manager:
                    return jsonify({
                        'success': False,
                        'error': '通知管理未启用'
                    }), 400
                
                status = self.dashboard.notification_manager.get_notifier_status()
                
                return jsonify({
                    'success': True,
                    'data': status
                })
            except Exception as e:
                self.logger.error(f"获取通知器状态失败: {e}")
                return jsonify({
                    'success': False,
                    'error': str(e)
                }), 500
        
        # 发送测试通知
        @self.bp.route('/notifications/test', methods=['POST'])
        def send_test_notification():
            """发送测试通知"""
            try:
                if not self.dashboard.notification_manager:
                    return jsonify({
                        'success': False,
                        'error': '通知管理未启用'
                    }), 400
                
                data = request.get_json() or {}
                notifier_type = data.get('type', 'email')
                message = data.get('message', 'XCQuant系统测试通知')
                
                success = self.dashboard.notification_manager.send_notification(
                    title='测试通知',
                    message=message,
                    level='info',
                    notifier_types=[notifier_type]
                )
                
                return jsonify({
                    'success': success,
                    'message': '测试通知已发送' if success else '测试通知发送失败'
                })
            except Exception as e:
                self.logger.error(f"发送测试通知失败: {e}")
                return jsonify({
                    'success': False,
                    'error': str(e)
                }), 500
        
        # 导出数据
        @self.bp.route('/export')
        def export_data():
            """导出监控数据"""
            try:
                format_type = request.args.get('format', 'json')
                time_range = int(request.args.get('hours', 24))
                
                data = self.dashboard.export_data(format_type, time_range)
                
                # 设置响应头
                filename = f"xcquant_export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.{format_type}"
                
                response = current_app.response_class(
                    data,
                    mimetype='application/json' if format_type == 'json' else 'text/plain',
                    headers={
                        'Content-Disposition': f'attachment; filename={filename}'
                    }
                )
                
                return response
            except Exception as e:
                self.logger.error(f"导出数据失败: {e}")
                return jsonify({
                    'success': False,
                    'error': str(e)
                }), 500
        
        # 配置管理
        @self.bp.route('/config')
        def get_config():
            """获取系统配置"""
            try:
                # 返回安全的配置信息（不包含敏感数据）
                config = {
                    'system': {
                        'name': 'XCQuant',
                        'version': '1.0.0',
                        'timezone': 'Asia/Shanghai'
                    },
                    'monitoring': {
                        'cache_ttl': self.dashboard.cache_ttl,
                        'refresh_interval': self.dashboard.config.get('refresh_interval', 5)
                    }
                }
                
                return jsonify({
                    'success': True,
                    'data': config
                })
            except Exception as e:
                self.logger.error(f"获取配置失败: {e}")
                return jsonify({
                    'success': False,
                    'error': str(e)
                }), 500
        
        # 更新配置
        @self.bp.route('/config', methods=['PUT'])
        def update_config():
            """更新系统配置"""
            try:
                data = request.get_json() or {}
                
                # 更新监控配置
                if 'monitoring' in data:
                    monitoring_config = data['monitoring']
                    if 'cache_ttl' in monitoring_config:
                        self.dashboard.cache_ttl = monitoring_config['cache_ttl']
                    if 'refresh_interval' in monitoring_config:
                        self.dashboard.config['refresh_interval'] = monitoring_config['refresh_interval']
                
                return jsonify({
                    'success': True,
                    'message': '配置已更新'
                })
            except Exception as e:
                self.logger.error(f"更新配置失败: {e}")
                return jsonify({
                    'success': False,
                    'error': str(e)
                }), 500